import os,json,time

from pydub import AudioSegment
from pydub.silence import split_on_silence

class Worker(object):
    def __init__(self):
        print("coze.worker.__init__")
        self.cmd_run = """
        curl 'https://modelscope.cn/api/v1/models/iic/{model}/widgets/submit' \
        -s --data-raw '{{"model_revision":"{version}","task":"{task}","inputs":["{input}"],"parameters":{{}},"urlPaths":{{"inUrls":[{{"type":"audio","fileType":"wav"}}]}}}}'
        """

        self.cmd_get = """
         curl 'https://modelscope.cn/api/v1/models/iic/{model}/widgets/query' \
         -s --data-raw '{{"id":"{execute_id}"}}'
        """

        self.workflow_ids={
            "audio2text":{"task":"auto-speech-recognition", "model":"speech_paraformer-large-vad-punc_asr_nat-zh-cn-16k-common-vocab8404-pytorch", "version":"v2.0.4", "input":""},
        }

    def proc(self, workflow, input):
        print(f"{workflow}:{input}")
        parms = self.workflow_ids.get(workflow)
        parms["input"] = input
        cmd1 = self.cmd_run.format(**parms)
        lines = os.popen(cmd1).readlines()
        res0 = json.loads("".join(lines))
        # print(res0)
        execute_id = res0.get("RequestId")
        executeStatus = ""
        cmd2 = self.cmd_get.format(execute_id=execute_id, model=parms.get("model"))
        # print(cmd2)
        while executeStatus == "":
            lines = os.popen(cmd2.replace("#execute_id#", execute_id)).readlines()
            res = json.loads("".join(lines))
            executeStatus = res.get("Data").get("computation_time")
            time.sleep(2)
        # print(res)
        nodeResults = res.get("Data").get("data").get("text")
        return {"result": nodeResults}

if __name__ == "__main__":
    worker = Worker()
    res = worker.proc("audio2text","https://audio.nndou.com/static/test.wav")
    print(res)
